#include "MusicListManager.h"

USING_NS_CC;

MusicListManager::MusicListManager()
{
	sqlite3_open("music.db", &pdb);
}

MusicListManager::~MusicListManager()
{
	sqlite3_close(pdb);
}

void MusicListManager::loadAll()
{
	char *setsql = "select setid,title,artist from music_set order by title";
	char **setdata;
	int setrow;
	sqlite3_get_table(pdb, setsql, &setdata, &setrow, NULL, NULL);
	for (int i = 1; i <= setrow; i++)
	{
		MUSICSETINFO data;
		data.id = setdata[i * 3];
		data.title = setdata[i * 3 + 1];
		data.artist = setdata[i * 3 + 2];
		char *notesql = sqlite3_mprintf("select backgroundfile from music_note where setid=%s", data.id.c_str());
		char **notedata;
		int noterow;
		sqlite3_get_table(pdb, notesql, &notedata, &noterow, NULL, NULL);
		sqlite3_free(notesql);
		data.coverPath = notedata[1];
		sqlite3_free(notedata);
		listdata.push_back(data);
	}
	sqlite3_free(setdata);
}

MusicLevelListManager::MusicLevelListManager()
{
	sqlite3_open("music.db", &pdb);
}

MusicLevelListManager::~MusicLevelListManager()
{
	sqlite3_close(pdb);
}

void MusicLevelListManager::loadList(string id)
{
	listdata.clear();
	char *setsql = sqlite3_mprintf("select ID,KEYS,BPMMAX,BPMMIN,BACKGROUNDFILE,NOTER,DIFFICULTY,LEVEL,LASTPLAYED,HIGHSCORE,HIGHEVALUATION,HIGHACCURACY,ISFULLCOMBO,ISCLEARED,NOTEFILE,FILETYPE\
 from music_note where setid=%s order by KEYS,LEVEL", id.c_str());
	char **setdata;
	int setrow;
	sqlite3_get_table(pdb, setsql, &setdata, &setrow, NULL, NULL);
	CCLOG(*setdata);
	for (int i = 1; i <= setrow; i++)
	{
		MUSICLEVELINFO data =
		{
			setdata[i * 16],
			setdata[i * 16 + 1],
			setdata[i * 16 + 2],
			setdata[i * 16 + 3],
			setdata[i * 16 + 4] == NULL ? "" : setdata[i * 16 + 4],
			setdata[i * 16 + 5],
			setdata[i * 16 + 6],
			setdata[i * 16 + 7],
			setdata[i * 16 + 8] == NULL ? "" : setdata[i * 16 + 8],
			setdata[i * 16 + 9] == NULL ? "" : setdata[i * 16 + 9],
			setdata[i * 16 + 10] == NULL ? "" : setdata[i * 16 + 10],
			setdata[i * 16 + 11] == NULL ? "" : setdata[i * 16 + 11],
			setdata[i * 16 + 12] == NULL ? "" : setdata[i * 16 + 12],
			setdata[i * 16 + 13] == NULL ? "" : setdata[i * 16 + 13],
			setdata[i * 16 + 14],
			setdata[i * 16 + 15]
		};
		listdata.push_back(data);
	}
	sqlite3_free(setsql);
	sqlite3_free(setdata);
}
